package cn.xianyang.pet.service.impl;

import cn.xianyang.basic.exception.BusinessException;
import cn.xianyang.basic.service.impl.BaseServiceImpl;
import cn.xianyang.basic.util.*;
import cn.xianyang.org.domain.Shop;
import cn.xianyang.org.mapper.ShopMapper;
import cn.xianyang.pet.domain.OrderPetAcquisition;
import cn.xianyang.pet.domain.Pet;
import cn.xianyang.pet.domain.SearchMasterMsg;
import cn.xianyang.pet.domain.SearchMasterMsgAuditLog;
import cn.xianyang.pet.dto.HandleMsgDto;
import cn.xianyang.pet.mapper.OrderPetAcquisitionMapper;
import cn.xianyang.pet.mapper.PetMapper;
import cn.xianyang.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.xianyang.pet.mapper.SearchMasterMsgMapper;
import cn.xianyang.pet.service.ISearchMasterMsgService;
import cn.xianyang.user.domain.Logininfo;
import cn.xianyang.user.domain.User;
import cn.xianyang.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xianyang
 * @since 2022-06-28
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    /**
     * 发布寻主消息实现
     * @param msg
     * @param logininfo
     */
    @Override
    public void publish(SearchMasterMsg msg, Logininfo logininfo) {
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //一。保存寻主消息
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
        //二。审核--系统自动审核Title标题
        String str = msg.getTitle() + msg.getName() + msg.getCoatColor() + msg.getAddress();
        if (!BaiduAuditUtils.TextCensor(str)){
            //审核不通过，给一次重新提交的机会，记录审核日志
            msg.setState(-1);
            //记录日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setNote("审核失败，存在敏感信息，原因可能是：标题，名字，毛色，地址等。");
            //发送审核失败邮件，提醒客人重新修改并提交审核
            //SmsUtils.senSms(user.getPhone(),"尊敬的用户："+ user.getPhone() + ",您的寻主消息内容不通过，请重新发布！");
            System.out.println(("尊敬的用户：" + user.getPhone() + ",您的寻主消息内容不通过，请重新发布！"));
            searchMasterMsgAuditLogMapper.save(log);
        }else {
            msg.setState(1);
            //审核通过-需要寻找附近50公里内的店铺
            //找到发布消息人的地址
            Point point = DistanceUtil.getPoint(msg.getAddress());
            //从所有门店中，找到离消息人最近的门店，设置范围50公里以内
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null){
                //找到就绑定shopid，给老板发送一条邮箱，提醒老板有新订单
                msg.setShopId(nearestShop.getId());
              //SmsUtils.senSms(nearestShop.getTel(),"尊敬的店主："+ nearestShop.getTel() + ",您有新的订单请及时处理！");
                System.out.println(("尊敬的店主：" + user.getPhone() + ",您有新的订单请及时处理！"));
            }
            //找不到，不管：不绑定店铺--> 寻主池
        }
        searchMasterMsgMapper.update(msg);
    }

    /**
     * 寻主消息接单业务实现
     * @param dto
     */
    @Override
    public void accept(HandleMsgDto dto) {
        //判断是否曾经被接单，根据msgId查询收购订单，还要判断状态是否是取消
        OrderPetAcquisition order =  orderPetAcquisitionMapper.loadByMsgIdAndNotCancel(dto.getMsgId());
        if(order != null){
            throw new BusinessException("此订单已被接单！！");
        }
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(dto.getMsgId());

        //1.生成宠物
        Pet pet = initPet(dto,msg);
        petMapper.save(pet);
        //2.生成收购单
        //抽取方法  快捷键alt + shift +m
        order = initOrderPetAcquisition(dto, msg, pet);
        orderPetAcquisitionMapper.save(order);

    }

    private OrderPetAcquisition initOrderPetAcquisition(HandleMsgDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition order;
        order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        order.setDigest(pet.getName() + ":收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        //绑定收购人
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet initPet(HandleMsgDto dto, SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setTypeId(msg.getPetType());
        pet.setShopId(msg.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(id);
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
    }
}
